﻿namespace DotNetOpenAuth.Samples.OAuthConsumerWpf
{
    using System;
    using System.Windows;
    using DotNetOpenAuth.OAuth;
    using OAuth.Messages;

    public partial class Authorize : Window
    {
        private readonly DesktopConsumer consumer;
        private readonly string requestToken;

        internal Authorize(DesktopConsumer consumer, FetchUri fetchUriCallback)
        {
            InitializeComponent();
            this.consumer = consumer;

            // Cursor original = this.Cursor;
            // this.Cursor = Cursors.Wait;

            // ThreadPool.QueueUserWorkItem(delegate(object state)
            // {
                Uri browserAuthorizationLocation = fetchUriCallback(this.consumer, out this.requestToken);

                this.webBrowser.Navigate(new Uri(browserAuthorizationLocation.AbsoluteUri));

            // System.Diagnostics.Process.Start(browserAuthorizationLocation.AbsoluteUri);
            //    this.Dispatcher.BeginInvoke(new Action(() => { this.Cursor = original; finishButton.IsEnabled = true; }));
            // });
        }

        internal delegate Uri FetchUri(DesktopConsumer consumer, out string requestToken);

        internal string AccessToken { get; set; }

        private void FinishButton_Click(object sender, RoutedEventArgs e)
        {
            AuthorizedTokenResponse grantedAccess = this.consumer.ProcessUserAuthorization(this.requestToken, verifierBox.Text);
            this.AccessToken = grantedAccess.AccessToken;
            this.DialogResult = true; 
            this.Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }
    }
}